package com.yy.controller;

import com.alibaba.fastjson2.JSON;
import com.yy.ex.BusinessException;
import com.yy.model.Result;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 描述
 * 作者 yy
 */
@RestController
@RequestMapping("admin/file")
@Log4j2
@Api(tags = "文件上传相关接口")
public class FileController {

    /**
     * 文件上传
     */
    @PostMapping("upload/element")
    @ApiOperation(value = "上传文件")
    public Result<String> upload(@RequestParam("file") MultipartFile file){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = "JIYaAcGMqHqocS057XtowbZjUWqFjrHQlX735Lo4";
        String secretKey = "rlLTwWmfwjiHEuGBFHQNVaT3XsHoQ4lBbYCXeX4J";
        String bucket = "yy-mall";
        String key = null;
        //登录到七牛云
        Auth auth = Auth.create(accessKey, secretKey);
        //获取登录之后的token
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(),DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            String realUrl="http://s4rrmekch.hn-bkt.clouddn.com/"+putRet.hash;
            return Result.success(realUrl);
        } catch (QiniuException ex) {
            log.error("上传失败{}",ex.getMessage());
            throw new BusinessException("上传失败:"+ex.getMessage());
        } catch (IOException e) {
            log.error("上传失败{}",e.getMessage());
            throw new BusinessException("上传失败:"+e.getMessage());
        }
    }
}
